package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    public DishService dishService;
    @Autowired
    public DishFlavorService dishFlavorService;
    @Autowired
    public CategoryService categoryService;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveW(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> list(int page,int pageSize,String name){
        //创建分页查询器Dish
        Page<Dish> dishPage=new Page<>(page,pageSize);
        //创建分页查询器DishDto
        Page<DishDto> dishDtoPage=new Page<>();
        //创建条件查询器
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        //使用模糊查询
        queryWrapper.like(name!=null,Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //MP分页查询 直接返回给分页查询器
        dishService.page(dishPage, queryWrapper);
        //对象拷贝，同时跳过records字段
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        //拿出Dish分页查询器里面的集合，就是Dish对象
        List<Dish> records = dishPage.getRecords();
        //使用《思君暮流》 拿出每个对象重新命名为tmp
        List<DishDto> lists =records.stream().map((tmp)->{
            //创建一个DishDto对象
            DishDto dishDto=new DishDto();
            //拷贝
            BeanUtils.copyProperties(tmp,dishDto);
            //拿出Dish里面的菜品分类id
            Long categoryId = tmp.getCategoryId();
            //在菜品分类管理表里面查询 查看有没有分类 并拿出此分类
            Category category = categoryService.getById(categoryId);
            //判断是否为空
            if (category!=null){
                //不为空 就将此分类的名称get出来
                String categoryName = category.getName();
                //将名称赋值给dishDto
                dishDto.setCategoryName(categoryName);
            }
            //返回 封装到list集合中
            return dishDto;
        }).collect(Collectors.toList());
        //将封装好的集合再次set到分页查询器中 因为我们将返回分页查询器
        dishDtoPage.setRecords(lists);
        //返回查询器
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    @PutMapping
    public R<String> put(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功！");
    }

    @GetMapping("/list")
    public R<List<DishDto>> get(Dish dish){

        List<DishDto> dishDtoList =null;
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加查询条件状态为1的
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByAsc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList =list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category !=null){
                String categoryName=category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品id
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,id);
            List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper);

            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }

    /**
     * 起售和停售
     * @param ids
     * @return
     */
    @PostMapping("/status/{ids}")
    public R<String> post(@RequestParam Long[] ids){
        log.info(ids.toString());
        for (Long id : ids) {
            LambdaQueryWrapper<Dish> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(Dish::getId,id);
            Dish dish = dishService.getOne(wrapper);
            if (dish.getStatus()==0){
                Integer status=1;
                dish.setStatus(status);
                dishService.updateById(dish);
            }else {
                Integer status=0;
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }
        return R.success("修改成功");
    }

    /**
     * 删除与批量删除
     * @param ids
     * @return
     */
    @DeleteMapping()
    public R<String> deletes(@RequestParam Long[] ids){
        log.info(ids.toString());
        for (Long id : ids) {
            dishService.removeById(id);
            LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId,id);
            List<DishFlavor> list = dishFlavorService.list(wrapper);
            for (DishFlavor dishFlavor : list) {
                dishFlavorService.removeById(dishFlavor);
            }
        }
        return R.success("删除成功");
    }

}
